//
//  PhotoPageView.m
//  Malena
//
//  在图片数量大于等于三张的情况下进行循环滚动，低于三张的情况不予处理
//  
//  Created by Wang Shuguang on 12-11-06.
//  Copyright 2012 Dawn. All rights reserved.
//

#import "PhotoPageView.h"
#import  <QuartzCore/QuartzCore.h>

@interface PhotoPageView(private)
- (void) addPhotos:(NSArray *)urls;
- (void) pageUp;
- (void) pageDown;
- (void) zoomToPointInRootView:(CGPoint)center atScale:(float)scale;
- (void) pageSwitchView:(NSInteger)index_0 withIndex:(NSInteger)index_1 andIndex:(NSInteger)index_2;
@end

#define PHOTO_NEAR_NUM 3
#define	PHOTO_MAX_ZOOM_SCALE 3
#define PHOTO_MIN_ZOOM_SCALE 1
#define PHOTO_TAP_MAX_ZOOM_SCALE 2
#define TIMER_INTERVAL 5
@implementation PhotoPageView
@synthesize photoFiles;
@synthesize currentPhotoUrl;
@synthesize delegate;
@synthesize page;

- (void)dealloc {
    [imagesArray release],imagesArray = nil;
    [photoFiles release],photoFiles = nil;
    [super dealloc];
}


- (id)initWithFrame:(CGRect)frame files:(NSArray *)files{
	self = [super initWithFrame:frame];
    if (self) {
		
		page = 0;
        self.photoFiles = files;

        pageEnabled = YES;
		isScaled = NO;
        photoViewSize = CGSizeMake(frame.size.width, frame.size.height);
		
		if (files) {
			photoCount = [files count];
		}else {
			photoCount = 3;
		}
		
		//主图片滚动区 图片两边留白
        photoScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,frame.size.width,frame.size.height)];
		photoScrollView.showsVerticalScrollIndicator = NO;
		photoScrollView.showsHorizontalScrollIndicator = NO;
		photoScrollView.pagingEnabled = YES;
		photoScrollView.delegate = self;
		photoScrollView.contentSize = CGSizeMake(MIN(photoCount,3) * frame.size.width,frame.size.height);
		[self addSubview:photoScrollView];
		[photoScrollView release];
		
		imagesArray = [[NSMutableArray alloc] initWithCapacity:files.count];
		[self addPhotos:files];
        
        //timer自动轮播
		timer = [NSTimer scheduledTimerWithTimeInterval:TIMER_INTERVAL target:self selector:@selector(photoAutoScroll) userInfo:nil repeats:YES];
		[self stopAutoScroll]; //暂停执行
	}
    return self;
	
}

#pragma mark -
#pragma mark - Properties
-(NSString *) currentPhotoUrl{
	return [photoFiles objectAtIndex:page];
}
-(UIImage *)currentImage{
    UIImageView *imageView = (UIImageView *)[imagesArray objectAtIndex:1];
    if (imageView && imageView.image) {
        return imageView.image;
    }
    return nil;
}

#pragma mark -
#pragma mark Reload photos
-(void) addPhotos:(NSArray *)files{
	//对于图片数量小于三的情况添加所有图片，对于图片数量大于三的情况只添加三张图片
	for (int i = 0; i < MIN(photoCount,3); i++) {
		NSInteger x = photoViewSize.width * i;
		NSInteger y = 0;
		
				
        // 图片缩放容器
		UIScrollView *scaleView = [[UIScrollView alloc] initWithFrame:CGRectMake(x, y, photoViewSize.width, photoViewSize.height)];
        scaleView.delegate = self;
        scaleView.bouncesZoom = YES;
        scaleView.showsVerticalScrollIndicator = NO;
        scaleView.showsHorizontalScrollIndicator = NO;
        scaleView.minimumZoomScale = PHOTO_MIN_ZOOM_SCALE;
        scaleView.maximumZoomScale = PHOTO_MAX_ZOOM_SCALE;
        scaleView.contentSize = CGSizeMake(photoViewSize.width, photoViewSize.height);
        scaleView.zoomScale = PHOTO_MIN_ZOOM_SCALE;
        [photoScrollView addSubview:scaleView];
        [scaleView release];
        
        // 图片容器
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, photoViewSize.width, photoViewSize.height)];
        imageView.userInteractionEnabled = YES;
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [scaleView addSubview:imageView];
        
        // 双击手势
        UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imgDoubleTap:)];
        doubleTap.numberOfTapsRequired = 2;
        doubleTap.numberOfTouchesRequired = 1;
        [imageView addGestureRecognizer:doubleTap];
        [doubleTap release];
       
        
        // 单击手势
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imgSingleTap:)];
        singleTap.numberOfTapsRequired = 1;
        singleTap.numberOfTouchesRequired = 1;
        [singleTap requireGestureRecognizerToFail:doubleTap];
        [imageView addGestureRecognizer:singleTap];
        [singleTap release];

		
        NSString *nsFile = nil;
        //当图片数量大于三的情况下把最后一张放在第一张的位置
        if (photoCount>=3) {
            if (files) {
				if (i==0) {
					nsFile = [files objectAtIndex:(photoCount - 1)];
				}else {
					nsFile = [files objectAtIndex:(i-1)];
				}
            }
            [photoScrollView setContentOffset:CGPointMake(photoViewSize.width, 0)];
        }else {
            if (files) {
                nsFile = [files objectAtIndex:i];
            }
            
            [photoScrollView setContentOffset:CGPointMake(0, 0)];
        }	  
		if (nsFile) {
            UIImage *image = [[UIImage alloc] initWithContentsOfFile:nsFile];
            imageView.image = image;
            [image release];
        }
		[imagesArray addObject:imageView];
		[imageView release];
        
	}
}

-(void) reloadDataWith:(NSArray *)files{
    if (files) {
        self.photoFiles = files;
    }
	if (photoFiles) {
		photoCount = [photoFiles count];
        page = 0;
		photoScrollView.contentSize = CGSizeMake(MIN(photoCount,3) * photoViewSize.width,photoViewSize.height);
		if (photoCount==0) {
			photoScrollView.hidden = YES;
		}
	}else{
		photoCount = 0;
		photoScrollView.contentSize = CGSizeZero;
		photoScrollView.hidden = YES;
		return;
	}
    //重置要显示的图片
    for (int i = 0; i < MIN(photoCount, 3); i++) {
        UIImageView *imageView =(UIImageView *)[imagesArray objectAtIndex:i];
      
		UIScrollView *scaleView = (UIScrollView *)[imageView superview];
        scaleView.frame = CGRectMake(i * photoViewSize.width, 0, photoViewSize.width, photoViewSize.height);
        scaleView.zoomScale = scaleView.minimumZoomScale;
        scaleView.contentSize = photoViewSize;
        
        imageView.frame = CGRectMake(0, 0, photoViewSize.width, photoViewSize.height);
        
        //当图片数量大于三的情况下把最后一张放在第一张的位置
        NSString *nsFile;
        if (photoCount>=3) {
			if (i==0) {
				nsFile = [photoFiles objectAtIndex:(photoCount - 1)];
			}else {
				nsFile = [photoFiles objectAtIndex:(i-1)];
			}
            
			[photoScrollView setContentOffset:CGPointMake(photoViewSize.width, 0)];
        }else {
            nsFile = [photoFiles objectAtIndex:i];
            
            [photoScrollView setContentOffset:CGPointMake(0, 0)];
        }
        
        UIImage *image = [[UIImage alloc] initWithContentsOfFile:nsFile];
        imageView.image = image;
        [image release];
    }
}

#pragma mark -
#pragma mark 图片自动轮播
-(void) photoAutoScroll{
	//[self pageToIndex:page +1];
    [self pageToIndex:page + 1 animated:NO];
}

-(void) stopAutoScroll{
	[timer setFireDate:[NSDate distantFuture]];
}

-(void) startAutoScroll{
	[timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:TIMER_INTERVAL]];
}



#pragma mark -
#pragma mark GestureRecognizer on photo
		 
- (void)imgDoubleTap:(UIGestureRecognizer *)gestureRecognizer{	
	
	
	UIImageView *imageView = [imagesArray objectAtIndex:1];
	if (imageView.frame.size.width<=20) {
		return;
	}
	UIScrollView *scrollView = (UIScrollView *)[imageView superview];
	
	CGPoint point = [gestureRecognizer locationOfTouch:0 inView:imageView];
	if(isScaled == YES){
		[self zoomToPointInRootView:point atScale:scrollView.minimumZoomScale];
		isScaled = NO;
	}else{
		[self zoomToPointInRootView:point atScale:PHOTO_TAP_MAX_ZOOM_SCALE];
		isScaled = YES;
	}
}	

-(void)imgSingleTap:(UIGestureRecognizer *)gestureRecognizer{
	if ([delegate respondsToSelector:@selector(photoPageView:didSelectedAtIndex:)]) {
		[delegate photoPageView:self didSelectedAtIndex:page];
	}
}



#pragma mark -
#pragma mark Private method
-(UITapGestureRecognizer *)doubleTap{
	UIImageView *imageView =(UIImageView *)[imagesArray objectAtIndex:1];
	return [imageView.gestureRecognizers objectAtIndex:0];
}

- (void)zoomToPointInRootView:(CGPoint)center atScale:(float)scale {
	
	UIImageView *imageView = [imagesArray objectAtIndex:1];
	UIScrollView *scrollView = (UIScrollView *)[imageView superview];
    CGRect zoomRect;
	
    zoomRect.size.height = scrollView.frame.size.height / scale;
	
    zoomRect.size.width  = scrollView.frame.size.width  / scale;
	
    zoomRect.origin.x    = center.x - (zoomRect.size.width  / 2.0);
	
    zoomRect.origin.y    = center.y - (zoomRect.size.height / 2.0);
	
	
    [scrollView zoomToRect:zoomRect animated:YES];
	
}

-(void) pageDown{
	NSInteger tpage = page + 1;
	
	for (int i = 0; i < 3 - 1; i++) {
		[imagesArray exchangeObjectAtIndex:i withObjectAtIndex:i+1];
	}
	for (int i = 0; i < 3; i++) {
		NSInteger x = photoViewSize.width * i;
		NSInteger y = 0;
		
        // 还原缩放
        UIScrollView *scaleView = (UIScrollView *)[((UIImageView *)[imagesArray objectAtIndex:i]) superview];
        scaleView.frame = CGRectMake(x, y, photoViewSize.width, photoViewSize.height);
        scaleView.zoomScale = scaleView.minimumZoomScale;
        scaleView.contentSize = photoViewSize;
	}
	
	UIImageView *imageView = (UIImageView *)[imagesArray objectAtIndex:2];
    if (tpage < photoCount) {
		UIImage *image = [[UIImage alloc] initWithContentsOfFile:[photoFiles objectAtIndex:tpage]];
        imageView.image = image;
        [image release];
	}else {
        UIImage *image = [[UIImage alloc] initWithContentsOfFile:[photoFiles objectAtIndex:tpage - photoCount]];
        imageView.image = image;
        [image release];
	}
	[photoScrollView setContentOffset:CGPointMake(photoScrollView.contentOffset.x - photoViewSize.width, 0)];
	
	
}
-(void) pageUp{
    NSInteger tpage = page - 1;
	for (int i = 3 - 1; i > 0; i--) {
		[imagesArray exchangeObjectAtIndex:i withObjectAtIndex:i-1];
	}
	for (int i = 0; i < 3; i++) {
		NSInteger x = photoViewSize.width * i;
		NSInteger y = 0;
		
		UIScrollView *scaleView = (UIScrollView *)[((UIImageView *)[imagesArray objectAtIndex:i]) superview];
        scaleView.frame = CGRectMake(x, y, photoViewSize.width, photoViewSize.height);
        scaleView.zoomScale = scaleView.minimumZoomScale;
        scaleView.contentSize = photoViewSize;
	}
	
    UIImageView *imageView = [imagesArray objectAtIndex:0];
	if (tpage >= 0) {
		UIImage *image = [[UIImage alloc] initWithContentsOfFile:[photoFiles objectAtIndex:tpage]];
        imageView.image = image;
        [image release];
	}else {
        UIImage *image = [[UIImage alloc] initWithContentsOfFile:[photoFiles objectAtIndex:tpage + photoCount]];
        imageView.image = image;
        [image release];
	}
	[photoScrollView setContentOffset:CGPointMake(photoScrollView.contentOffset.x + photoViewSize.width, 0)];
}

#pragma mark -
#pragma mark Public method
-(void) pageToIndex:(NSInteger)index{
    if (index != page) {
		//对于过长的情况，进行处理
		if (index - page > PHOTO_NEAR_NUM) {
			page = index - PHOTO_NEAR_NUM;
		}else if (page - index > PHOTO_NEAR_NUM) {
			page = PHOTO_NEAR_NUM + index;
		}
        pageEnabled = NO;
		[photoScrollView setContentOffset:CGPointMake((index - page)*photoViewSize.width + photoScrollView.contentOffset.x, 0) animated:YES];
	}
}

- (void)pageAction{
    UIImageView *imageView = [imagesArray objectAtIndex:1];
    
    [UIView beginAnimations:nil context:nil];
   // [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    [UIView setAnimationDuration:1.2];
    imageView.alpha = 1.0f;
    [UIView commitAnimations];
    
    [self performSelector:@selector(removeCurrentImageView) withObject:nil afterDelay:0.3];
    
}

- (void) removeCurrentImageView{
    if (currentImageView) {
        [currentImageView removeFromSuperview];
        currentImageView = nil;
    }
}

- (void) pageSwitchView:(NSInteger)index_0 withIndex:(NSInteger)index_1 andIndex:(NSInteger)index_2{
    // 第一张图
    UIImageView *imageView = [imagesArray objectAtIndex:0];
    UIImage *image = nil;
    image = [[UIImage alloc] initWithContentsOfFile:[photoFiles objectAtIndex:index_0]];
    imageView.image = image;
    [image release];
    // 第二张图
    imageView = [imagesArray objectAtIndex:1];
    
    currentImageView = [[UIImageView alloc] initWithFrame:CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y, imageView.frame.size.width, imageView.frame.size.height)];
    currentImageView.image = [UIImage imageWithCGImage:imageView.image.CGImage];
    currentImageView.contentMode = UIViewContentModeScaleAspectFit;
    [[imageView superview] addSubview:currentImageView];
    [currentImageView release];
    
    image = [[UIImage alloc] initWithContentsOfFile:[photoFiles objectAtIndex:index_1]];
    imageView.image = image;
    [image release];
    imageView.alpha = 0;
    
    [UIView beginAnimations:nil context:nil];
    //[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    [UIView setAnimationDuration:1.2];
    currentImageView.alpha = 0.0f;
    [UIView commitAnimations];
    [self performSelector:@selector(pageAction) withObject:nil afterDelay:1.0];
    // 第三张图
    imageView = [imagesArray objectAtIndex:2];
    image = [[UIImage alloc] initWithContentsOfFile:[photoFiles objectAtIndex:index_2]];
    imageView.image = image;
    [image release];
}

- (void) quickPageSwitchView:(NSInteger)index_0 withIndex:(NSInteger)index_1 andIndex:(NSInteger)index_2{
    // 第一张图
    UIImageView *imageView = [imagesArray objectAtIndex:0];
    UIImage *image = nil;
    image = [[UIImage alloc] initWithContentsOfFile:[photoFiles objectAtIndex:index_0]];
    imageView.image = image;
    [image release];
    // 第二张图
    imageView = [imagesArray objectAtIndex:1];
    image = [[UIImage alloc] initWithContentsOfFile:[photoFiles objectAtIndex:index_1]];
    imageView.image = image;
    [image release];
    // 第三张图
    imageView = [imagesArray objectAtIndex:2];
    image = [[UIImage alloc] initWithContentsOfFile:[photoFiles objectAtIndex:index_2]];
    imageView.image = image;
    [image release];
}

- (void) quickPageToIndex:(NSInteger)index{
    pageEnabled = NO;
	if (index >= photoCount) {
        index = 0;
    }else if(index < 0){
        index = photoCount - 1;
    }
    self.page = index;
    if (photoCount<3) {
        return;
    }
    if (index==0) {
        [self quickPageSwitchView:photoCount - 1 withIndex:0 andIndex:1];
    }else if (index == photoCount - 1) {
        [self quickPageSwitchView:photoCount - 2 withIndex:photoCount - 1 andIndex:0];
    }else {
        [self quickPageSwitchView:index - 1 withIndex:index andIndex:index + 1];
    }

}

-(void) pageToIndex:(NSInteger)index animated:(BOOL)animated{
    pageEnabled = NO;
	if (animated) {
		[self pageToIndex:index];
	}else {
        if (index >= photoCount) {
            index = 0;
        }else if(index < 0){
            index = photoCount - 1;
        }
		self.page = index;
		if (photoCount<3) {
			return;
		}
		if (index==0) {
            [self pageSwitchView:photoCount - 1 withIndex:0 andIndex:1];
        }else if (index == photoCount - 1) {
            [self pageSwitchView:photoCount - 2 withIndex:photoCount - 1 andIndex:0];
		}else {
            [self pageSwitchView:index - 1 withIndex:index andIndex:index + 1];
		}
	}
}

#pragma mark -
#pragma mark UIScrollViewDelegate

-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
	if (scrollView!=photoScrollView) {
		if ([imagesArray count]>=3) {
			UIImageView *imageView = (UIImageView *)[imagesArray objectAtIndex:1];
			if (!imageView.image) {
				return nil;
			}
		}
		
		if ([[scrollView subviews] count]>0) {
			return [[scrollView subviews] objectAtIndex:0];
		}else {
			return nil;
		}
	}else {
		return nil;
	}
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView{
	if (scrollView == photoScrollView) {
		return;
	}
	
	UIImageView *imgView = [[scrollView subviews] objectAtIndex:0];
	if (imgView.image == nil) {
		return;
	}
	
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?(scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?(scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    imgView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,scrollView.contentSize.height * 0.5 + offsetY);
	
	scrollView.contentSize = CGSizeMake(MAX(imgView.frame.size.width,photoViewSize.width),MAX(imgView.frame.size.height,photoViewSize.height));
    
    if ([delegate respondsToSelector:@selector(didZoomToScale:)]) {
		[delegate didZoomToScale:scrollView.zoomScale];
	}
}

-(void) scrollViewDidScroll:(UIScrollView *)scrollView{

	if (scrollView!=photoScrollView) {
		return;
	}
   
	NSInteger tpage = floor((scrollView.contentOffset.x - scrollView.frame.size.width / 2) / scrollView.frame.size.width) + 1;
	
	if (tpage == 0) {
        if (page - 1 >= 0) {
            page--;
        }else{
            page = photoCount - 1;
        }
    }else  if (tpage == 2) {
        if (page + 1 < photoCount) {
            page++;
        }else {
			page = 0;
        }
    }
	
	if (tpage == 0 || tpage == 2) {
        if (photoCount>=3) {
            if (tpage == 2) {
				[self pageDown];
            }else {
				[self pageUp];
            }
            if (pageEnabled) {
                if ([delegate respondsToSelector:@selector(photoPageView:didPagedToIndex:)]) {
                    [delegate photoPageView:self didPagedToIndex:page];
                }
            }
        }
    }
    
    
}

// At the begin of scroll dragging, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    pageEnabled = YES;
}

// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
	
}

-(void) scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
	
}

#pragma mark -
#pragma mark Layout Subviews
- (void) layoutSubviews{
    photoViewSize = CGSizeMake(self.frame.size.width, self.frame.size.height);
    photoScrollView.frame = CGRectMake(0, 0, photoViewSize.width, photoViewSize.height);
    photoScrollView.contentSize = CGSizeMake(MIN(photoCount,3) * photoViewSize.width , photoViewSize.height);
    photoScrollView.contentOffset = CGPointMake( photoViewSize.width, 0);
    for (int i = 0; i < 3; i++) {
		NSInteger x = photoViewSize.width * i;
		NSInteger y = 0;
		UIScrollView *scaleView = (UIScrollView *)[((UIImageView *)[imagesArray objectAtIndex:i]) superview];
        scaleView.frame = CGRectMake(x, y, photoViewSize.width, photoViewSize.height);
        scaleView.zoomScale = scaleView.minimumZoomScale;
        scaleView.contentSize = photoViewSize;
        
        UIImageView *imageView = (UIImageView *)[imagesArray objectAtIndex:i];
        imageView.frame = CGRectMake(0, 0, photoViewSize.width, photoViewSize.height);
	}
}
@end
